// 申请售后页面
import React, {Component} from 'react';
import {NativeModules, StatusBar, Text, View, Dimensions, FlatList, ImageBackground, Image, TouchableHighlight, TextInput, Button, StyleSheet, ScrollView, TouchableOpacity, PixelRatio, TouchableWithoutFeedback, Keyboard, TouchableNativeFeedback, DeviceEventEmitter} from 'react-native';
import Modal from 'react-native-modalbox';
import {RadioGroup, RadioButton} from 'react-native-flexi-radio-button'


import CXIcon from '../../../style/icon/CXIcon';
import styles, {mainBackgroundColor, white} from "../../../style/global";
import {is, fen_to_yuan, fen_money, getNowFormatDate} from '../../../utils';
import Tips from 'react-native-root-tips';
import {Actions} from 'react-native-router-flux';
import { ToastAndroid } from 'react-native';


import storeActions from '../../../store/actions/store';
import memberActions from '../../../store/actions/member';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';

class IndexPage extends Component{
    constructor(props) {
        super(props);
        this.state = {
            // 搜索内容
            searchText: '',
            userSearchText: '', // 会员搜索内容
            isVisible: false,
            order_no: '', //申请售后的订单编号
            // 当前商品数据列表
            currentList: [],
            refundContent: '', // 问题描述
            refundInfo: '',   // 申请缓存数据
            refundGoods: [], // 申请售后商品数据
            // 当前正在编辑的商品
            currentEditGoods: {},
            currentEditIndex: '',
            currentUser: '',  // 当前选择的会员
            currentCoupon: '', // 当前选择的优惠券
            currentCouponList: [],  // 当前可用优惠券列表
            currentDiscount: '', // 当前选中的促销折扣
            currentPercentDiscount: '',
            currentDiscountList: [], // 当前可用的促销折扣列表
            disObj: {}, // 每个促销能使用的商品列表
            disAmountList: [], // 每个促销能抵扣多钱钱
            store_count: 0, // 库存
            select_product: {},  // 当前选中的商品
            select_count: 1, // 选择的数量
            price: '',
            canBuy: false,
            disForm: '',
            page: 1,
            isLoadMore: false,
            userIsOpen: false,
            pointStatus: true

        };
        this.currentCoupon = '';
        this.result = null;
        this.skuTable = null;
        this.currentDiscount = '';
        this.currentPercentDiscount = '';
        this.discountList = [];
        this.oldCurrentDiscount = '';
    }
    componentDidMount() {
        this.setState({
            order_no: this.props.order_no || 'O2019050916891880825'
        });

        console.log('这个是获取到的订单编号', this.props.order_no);

        storage.load({
            key: 'refund-data'
        }).then(res => {
            if (res) {
                if (res.order_items) {
                    res.order_items.forEach(item => {
                        item.num = 1
                    });
                }
                this.setState({
                    refundInfo: res,
                    refundGoods: res.order_items ? res.order_items : [],
                    refundContent: res.reasons && res.reasons.length ? res.reasons[0] : ''
                }, () => {
                    this.filterDis();
                })
            }
            console.log('缓存中数据', res);
        }).catch(err => {
            console.log(err);
        });
    }
    // 搜索商品
    _searchGoods() {
        Keyboard.dismiss();
        if (!this.state.searchText) {
            Tips.show('请输入商品信息');
            return
        }

        let {storeAction} = this.props;
        storeAction.getStoreList(this.state.searchText, (res) => {
            if (res && res.status && res.data) {
                this.refs.searchModal.open();
            } else {
                this.refs.searchModal.close();
            }
        });
    }


    // 防抖函数
    _debounce(fn, wait) {
        var timer = null;
        return function () {
            var context = this;
            var args = arguments;
            console.log('这个是什么', timer, fn);
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            timer = setTimeout(function () {
                fn.apply(context, args)
            }, wait)
        }
    }
    _consoleValue() {
        console.log(444);
    };
    _inputBlur(index) {
        const list = this.state.currentList;
        const item = list[index];
        item.user_discount = item.user_discount ? item.user_discount : 0;
        item.discount_price = item.discount_price ? item.discount_price : 0;

        this.setState({
            currentList: list
        })
    }
    // 改变折扣以及折后价
    _changeDiscount(index, type, text) {
        let inputText = text.replace(/[^\d\.]|^\./g, '').replace(/\.{2}/g, '.').replace(/^([1-9]\d*|0)(\.\d{1,2})(\.|\d{1})?$/, '$1$2').replace(/^0\d{1}/g, '0');
        inputText = inputText ? Number(inputText) : '';
        const list = this.state.currentList;
        const item = list[index];
        // console.log('输入值', inputText, item.base_goods.market_price);

        // 改变折扣，计算折后价
        if (type == 'proportion') {
            if (inputText > 100) {
                ToastAndroid.showWithGravity('折扣不能超过100%', ToastAndroid.SHORT, ToastAndroid.CENTER);
                return
            } else {
                item.user_discount = inputText;
                item.discount_price = (((item.user_discount / 100) * (item.base_goods.market_price * 100)) / 100).toFixed(2);
            }
        } else {
            if (inputText > Number(item.base_goods.market_price)) {
                ToastAndroid.showWithGravity('折后价不能超过原价', ToastAndroid.SHORT, ToastAndroid.CENTER);
                return
            } else {
                item.discount_price = inputText;
                item.user_discount = (((inputText * 100) / (item.base_goods.market_price * 100)) * 100).toFixed(2);
                // item.user_discount = Number(parseFloat(inputText / item.base_goods.market_price * 100).toFixed(3).slice(0,-1))
            }
        }
        this.setState({
            currentList: list
        }, () => {
            this.filterDis(true)
        });
        // console.log(index, type,item, text);
    }
    // 赋值
    // 添加商品到列表
    _addGoods(item, num) {
        console.log(item);
        // let {}
        item.num = item.num || 1;
        item.goodsDisAmount = 0; // 当前商品参与活动抵扣的值
        item.fixed_user_discount = item.user_discount; // 重新赋值，打折时需要改变user_discount

        const list = this.state.currentList;
        let isAdd = false;
        if (!num) {
            ToastAndroid.showWithGravity('所选商品暂无库存', ToastAndroid.SHORT, ToastAndroid.CENTER);
            return
        }
        if (!list.length) {
            list.push(item);
        } else {
            list.forEach((items, index) => {
                // 当id相同时，数量加1
                if (items.id == item.id) {
                    items.num += 1;
                    isAdd = true
                }
            });

            // 当没有ID相同的，则新增数据
            if (!isAdd) {
                list.push(item);
            }
        }


        /*for (let key in disObj) {
            let value = disObj[key];
            disAmountList.push({
                [`${key}`]: 0
            });
            value.forEach(items => {
                disAmountList.forEach(money => {
                    if (Object.keys(money) == key) {
                        money[`${key}`] =  money[`${key}`] + items.base_goods.market_price * items.num;
                    }
                });
            });

            console.log('应该是对的', disAmountList);
        }*/

        item.discount_price = (item.user_discount / 100 * item.base_goods.market_price).toFixed(2);
        item.subtotal = (item.discount_price * item.num).toFixed(2);
        // 当该商品能使用积分时, 初始能使用积分的总额为小计总额
        if (item.point_deduction) {
            item.used_point_total = Math.signFigures(item.subtotal *100) - item.goodsDisAmount
        }


        console.log('列表数据', JSON.stringify(list));
        this.setState({
            currentList: list
        }, () => {
            // 筛选最优促销
            this.filterDis();
        });
    }

    // 筛选最优促销(暂时没用)
    filterDis(is_edit) {
        // 只执行小计计算
        this._checkSubtotal(true, 0, is_edit);
        return;
        /*
       disType：
       type = cash 减钱
       type = discount 打折

       actions中type值代表的意思：
       order_fixed_discount    订单减钱
       goods_fixed_discount    商品减钱
       order_percentage_discount   订单折扣
       goods_percentage_discount   商品折扣
       */

        const { storeState } = this.props;
        const list = this.state.currentList;
        let disObj = this.state.disObj;
        // 每个促销能使用的当前商品列表
        list.forEach((goods, index) => {
            // console.log('商品列表', JSON.stringify(goods), isSelf);
            const itemDisList = goods.discount_ids || [];  // 当前商品参与的促销id列表
            itemDisList.forEach((ids, index) => {
                let disArr = disObj[`${ids}`] || [];
                let isAdds = false;
                if (disObj[`${ids}`]) {
                    for (let value of disObj[`${ids}`]) {
                        if (value.id == goods.id) {
                            value = goods;
                            isAdds = true;
                            break;
                        }
                    }
                    if (!isAdds) {
                        disArr.push(goods);
                    }
                } else {
                    disArr.push(goods);
                }
                let newArr = disArr.slice(0);  // 赋值新数组
                disObj[`${ids}`] = newArr;
            });
        });


        // return
        // 促销是否能用于当前列表，以及能抵扣的金额
        storeState.discountInfo.forEach(dis => {
            let disType = dis.action_type.type;  // 促销类别
            let disValue = dis.action_type.value; // 促销数值
            let disAmount = dis.rule_type.amount; // 促销限制值
            let actionsType = dis.actions[0].type; // 促销具体类别

            dis.disAmount = 0;  // 当前可用于促销的商品总额（满减用）
            dis.disNum = 0; // 当前可用于促销的数量（满折用）
            dis.goodsAmount = 0;
            for (let key in disObj) {
                let value = disObj[key];
                value.forEach(items => {
                    if (dis.id == key) {
                        items.subtotal = (items.user_discount / 100 * items.base_goods.market_price * items.num).toFixed(2);
                        if (!is_edit) {
                            items.discount_price = (items.user_discount / 100 * items.base_goods.market_price).toFixed(2);
                        }
                        dis.disAmount = Number((dis.disAmount + items.subtotal * 100).toFixed(0));
                        dis.goodsAmount += Number(items.base_goods.market_price);

                        // console.log('能使用的', dis.disAmount, items.user_discount, isSelf);
                        dis.disNum += Number(items.num);
                    }
                });
            }

            if (disType == 'cash') {
                if (disAmount <= dis.disAmount) {
                    dis.isActive = true;
                    dis.disTotalAmount = Math.signFigures(disValue * 100);
                } else {
                    dis.isActive = false;
                    dis.disTotalAmount = 0;
                }
            } else {
                // 订单折扣
                if (disAmount <= dis.disNum) {
                    dis.isActive = true;
                    dis.disTotalAmount = Math.signFigures(dis.goodsAmount * 100) - dis.disAmount
                } else {
                    dis.isActive = false;
                    dis.disTotalAmount = 0;
                }
            }
        });

        console.log('折扣列表',JSON.stringify(storeState.discountInfo));
        // 筛选出最优的促销

        // 最优打折，最优减钱，先打折然后再减钱

        let percentDisList = this.percentagedisSort(storeState.discountInfo);
        let currentPercentDiscount = percentDisList.length ? percentDisList[percentDisList.length - 1] : '';
        this.currentPercentDiscount = currentPercentDiscount;


        // console.log('之前的促销',JSON.stringify(currentPercentDiscount));
        // 根据最优的促销处理相应的逻辑

        // 打折最优
        if (!is_edit) {
            if (currentPercentDiscount && currentPercentDiscount.action_type.type) {
                let disGoodList = disObj[currentPercentDiscount.id];
                let value = currentPercentDiscount.action_type.value;

                list.forEach(goods => {
                    // goods.user_discount = goods.fixed_user_discount;
                    goods.goodsDisAmount = 0; // 当前商品参与活动抵扣的值
                    disGoodList.forEach(item => {
                        if (goods.id == item.id) {
                            // let money = Math.signFigures(goods.base_goods.market_price * 100 * goods.num);
                            let money = Math.signFigures(goods.subtotal * 100);
                            let disValue = ((10 - value) / 10).toFixed(2);
                            goods.user_discount = Math.signFigures(value * 10);
                            // goods.goodsDisAmount = Math.signFigures(money * disValue);  // 每个商品减掉的钱
                            console.log('每个商品减掉的钱', goods.goodsDisAmount);
                            // goods.goodsDisAmount = Math.signFigures(money * value / 10)
                        }
                    })
                });
                // console.log('这个里面没跑1', JSON.stringify(list));

                // 由于使用了打折，需要重新计算一遍值


                // 每个促销能使用的当前商品列表
                list.forEach((goods, index) => {
                    // console.log('商品列表', JSON.stringify(goods), isSelf);
                    const itemDisList = goods.discount_ids || [];  // 当前商品参与的促销id列表
                    itemDisList.forEach((ids, index) => {
                        let disArr = disObj[`${ids}`] || [];
                        let isAdds = false;
                        if (disObj[`${ids}`]) {
                            for (let value of disObj[`${ids}`]) {
                                if (value.id == goods.id) {
                                    value = goods;
                                    isAdds = true;
                                    break;
                                }
                            }
                            if (!isAdds) {
                                disArr.push(goods);
                            }
                        } else {
                            disArr.push(goods);
                        }
                        let newArr = disArr.slice(0);  // 赋值新数组
                        disObj[`${ids}`] = newArr;
                    });
                });


                // console.log('列表', JSON.stringify(disObj));


                // 促销是否能用于当前列表，以及能抵扣的金额
                storeState.discountInfo.forEach(dis => {
                    let disType = dis.action_type.type;  // 促销类别
                    let disValue = dis.action_type.value; // 促销数值
                    let disAmount = dis.rule_type.amount; // 促销限制值
                    let actionsType = dis.actions[0].type; // 促销具体类别
                    dis.goodsAmount = 0;
                    dis.disAmount = 0;  // 当前可用于这张优惠券的商品总额（满减用）
                    dis.disNum = 0; // 当前可用于这张优惠券的数量（满折用）
                    for (let key in disObj) {
                        let value = disObj[key];
                        value.forEach(items => {
                            if (dis.id == key) {
                                items.subtotal = (items.user_discount / 100 * items.base_goods.market_price * items.num).toFixed(2);
                                if (disType == 'cash') {
                                    dis.disAmount = Number((dis.disAmount + items.subtotal * 100 - items.goodsDisAmount).toFixed(2));
                                } else {
                                    dis.disAmount = Number((dis.disAmount + items.subtotal * 100).toFixed(2));
                                }
                                console.log('能使用的', dis.disAmount, items.goodsDisAmount, items.user_discount);
                                dis.disNum += Number(items.num);
                                dis.goodsAmount += Number(items.base_goods.market_price);
                                // console.log('还剩下多少钱可以用', JSON.stringify(dis));
                            }
                        });
                    }
                    if (disType == 'cash') {
                        if (disAmount <= dis.disAmount) {
                            dis.isActive = true;
                            dis.disTotalAmount = Math.signFigures(disValue * 100);
                        } else {
                            dis.isActive = false;
                            dis.disTotalAmount = 0;
                        }
                    } else {
                        // 订单折扣
                        if (disAmount <= dis.disNum) {
                            dis.isActive = true;
                            dis.disTotalAmount = Math.signFigures(dis.goodsAmount * 100) - dis.disAmount
                        } else {
                            dis.isActive = false;
                            dis.disTotalAmount = 0;
                        }
                    }
                });

            } else {
                list.forEach(goods => {
                    goods.user_discount = goods.fixed_user_discount;
                    goods.goodsDisAmount = 0; // 当前商品参与活动抵扣的值
                });
            }
        }


        // console.log('优惠券', JSON.stringify(storeState.discountInfo));
        // console.log('列表', JSON.stringify(list));

        // 算减钱
        let goodDisList = this.disSort(storeState.discountInfo);
        let currentDiscount = goodDisList.length ? goodDisList[goodDisList.length - 1] : '';
        this.currentDiscount = currentDiscount;

        // 减钱最优
        if (currentDiscount && currentDiscount.action_type.type) {
            let disGoodList = disObj[currentDiscount.id];
            let value = Math.signFigures(currentDiscount.action_type.value * 100);  // 减掉的钱
            // console.log('这个是什么', disGoodList, isSelf);
            list.forEach(goods => {
                /*if (!currentPercentDiscount)  {
                    goods.user_discount = goods.fixed_user_discount;
                     // 当前商品参与活动抵扣的值
                }*/
                goods.goodsDisAmount = 0;
                disGoodList.forEach(item => {
                    if (goods.id == item.id) {
                        let user_discount = Math.signFigures(item.user_discount / 100 );
                        let money = Math.signFigures(goods.subtotal * 100) - goods.goodsDisAmount; // 每个商品的价钱
                        let disAmount = currentDiscount.disAmount; // 当前促销可使用的商品的金额

                        // 如果是减钱，并且使用了打折
                        if (currentDiscount.action_type.type == 'cash') {
                            if (money / disAmount * value > money) {
                                goods.goodsDisAmount = goods.goodsDisAmount + money
                            } else {
                                goods.goodsDisAmount = money - Number((money / disAmount * value).toFixed(2)) + goods.goodsDisAmount;
                            }

                            console.log('减钱每个分摊', money - Number((money / disAmount * value).toFixed(2)));
                        }
                    }
                })
            });
        } else {
            if (!currentPercentDiscount) {
                list.forEach(goods => {
                    goods.user_discount = goods.fixed_user_discount;
                    goods.goodsDisAmount = 0; // 当前商品参与活动抵扣的值
                });
            }
        }


        // console.log('这个里面没跑3', Object.assign({}, list));
        console.log('打折最优', currentPercentDiscount);
        console.log('减钱最优', currentDiscount);

        // console.log('列表', JSON.stringify(list));
        this.setState({
            currentList: list,
            disObj: disObj,
            currentDiscount: currentDiscount,
            currentPercentDiscount: currentPercentDiscount
        }, () => {

            this._checkSubtotal(true,0,is_edit);
            /*if (!isSelf) {
                let oldCurrentDiscount = currentDiscount ? Object.assign({}, currentDiscount) : '';
                this.oldCurrentDiscount = oldCurrentDiscount;
                console.log('这个是旧的', oldCurrentDiscount);
                this.filterDis(true);
            }
            console.log('这个是新的', currentDiscount);
            this._checkDiscount();
            console.log('这个就是那个最优的', goodDisList[goodDisList.length - 1], isSelf);*/
        });
    }


    // 排序方法

    // 减钱排序, 按照谁减的多排序
    disSort(list) {
        console.log('处理前的数据', list);
        let newList = [];
        list.forEach(item => {
            if (item.isActive && item.action_type.type == 'cash') {
                newList.push(item);
            }
        });

        let len = newList.length;
        let minIndex, temp;
        for (let i = 0; i < len - 1; i++) {
            minIndex = i;
            for (let j = i + 1; j < len; j++) {
                if (newList[j].disTotalAmount < newList[minIndex].disTotalAmount) {     //寻找最小的数
                    minIndex = j;                 //将最小数的索引保存
                }
            }
            temp = newList[i];
            newList[i] = newList[minIndex];
            newList[minIndex] = temp;
        }
        return newList;
    }

    // 打折排序，按照件数排序
    percentagedisSort(list) {
        console.log('处理前的数据', list);
        let newList = [];
        list.forEach(item => {
            if (item.isActive && item.action_type.type == 'discount') {
                newList.push(item);
            }
        });

        let len = newList.length;
        let minIndex, temp;
        for (let i = 0; i < len - 1; i++) {
            minIndex = i;
            for (let j = i + 1; j < len; j++) {
                if (newList[j].disNum < newList[minIndex].disNum) {     //寻找最小的数
                    minIndex = j;                 //将最小数的索引保存
                }
            }
            temp = newList[i];
            newList[i] = newList[minIndex];
            newList[minIndex] = temp;
        }
        return newList;
    }

    // 改变换货数量
    _changeListNum(text, index) {
        const list = this.state.currentList;
        if (is.number(text)) {
            if (text <= list[index].store_nums) {
                list[index].num = text;
                this.setState({
                    currentList: list
                }, () => {
                    this.filterDis();
                });

                // this._checkSubtotal(false, index);
            } else {
                ToastAndroid.showWithGravity('库存不足', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        }
    }

    // 改变申请售后商品数量
    _changeRefundListNum(text, index) {
        const list = this.state.refundGoods;
        if (is.number(text)) {
            if (text <= list[index].quantity) {
                list[index].num = text;
                this.setState({
                    refundGoods: list
                }, () => {
                    this.filterDis();
                });

                // this._checkSubtotal(false, index);
            } else {
                ToastAndroid.showWithGravity('超过可申请数量', ToastAndroid.SHORT, ToastAndroid.CENTER)
            }

        }
    }

    // 删除数组
    _deleteListItem(index) {
        const list = this.state.currentList;
        const item = list[index];
        let disObj = this.state.disObj;
        list.splice(index, 1);
        if (disObj) {
            for (let key in disObj) {
                let value = disObj[key];
                value.forEach((good, idx) => {
                    if (good.id == item.id) {
                        value.splice(idx, 1)
                    }
                })
            }
        }
        this.setState({
            currentList: list,
            disObj: disObj
        }, () => {
            console.log('这个没有跑嘛');
            this.filterDis();
            this._checkDiscount();
        });
    }



    // 计算列表小计价格以及数量
    _checkSubtotal(isList,index,is_edit) {

        console.log('这个是什么', is_edit);
        const list = this.state.currentList;
        let disObj = this.state.disObj;
        const { storeState } = this.props;
        console.log('你猜这个有没有值：', list);
        if (isList) {
            list.forEach((item, index) => {
                if (!is_edit) {
                    item.discount_price = (item.user_discount / 100 * item.base_goods.market_price).toFixed(2);
                }
                item.subtotal = (item.discount_price * item.num).toFixed(2);
                // 计算总额
                item.itemTotalAmount = (item.base_goods.market_price * item.num).toFixed(2)


                // 当该商品能使用积分时, 初始能使用积分的总额为小计总额减去平摊到商品的促销金额
                if (item.point_deduction) {
                    item.used_point_total =  Math.signFigures(item.subtotal * 100) - item.goodsDisAmount
                }
            })
        } else {
            const item = list[index];
            if (!is_edit) {
                item.discount_price = (item.user_discount / 100 * item.base_goods.market_price).toFixed(2);
            }
            item.subtotal = (item.discount_price / 100 * item.base_goods.market_price * item.num).toFixed(2);
        }
        console.log('列表', JSON.stringify(list))
        this.setState({
            currentList: list
        }, () => {
            this._checkDiscount();
        });
    }

    // 计算优惠折扣以及商品数量价格
    _checkDiscount() {
        const list = this.state.currentList;
        const refundGoods = this.state.refundGoods;

        let disForm = {
            num: 0,  // 数量
            itemTotalAmount: 0,  // 总额
            discount_amount: 0, // 会员折扣优惠
            total_amount: 0, // 合计
            refund_amount: 0, // 退款金额
            spread_amount: 0 // 差价
        };
        refundGoods.forEach(item => {
            if (item.quantity != item.num) {
                item.subtotal = Math.floor(item.total / item.quantity * item.num)
            } else {
                item.subtotal = item.total
            }
            disForm.refund_amount += item.subtotal
        });
        list.forEach((item, index) => {
            disForm.itemTotalAmount += Number(item.itemTotalAmount);
            disForm.num += Number(item.num);
            disForm.total_amount += Number((item.subtotal * 100).toFixed(2));
            disForm.discount_amount += Math.signFigures(item.base_goods.market_price * 100 * item.num) - Math.signFigures(item.subtotal * 100);
        });
        disForm.spread_amount = disForm.total_amount - disForm.refund_amount;

        console.log(disForm);

        this.setState({
            disForm: disForm
        })










        /*const { storeState } = this.props;
        let userCoupon = [];  // 可用的优惠券列表
        const { memberState } = this.props;
        let disForm = {
            itemTotalAmount: 0,
            coupon_id: 0, // 选择的优惠券ID
            num: 0,  // 数量
            total_amount: 0, // 合计
            used_point_total_amount: 0, // 能使用积分的总额
            used_point: 0, // 使用的积分
            discount_fix_id: this.currentDiscount ? this.currentDiscount.id : 0, // 减钱促销id
            discount_id: this.currentPercentDiscount ? this.currentPercentDiscount.id : 0, // 打折促销id
            discount_amount: 0, // 折扣优惠
            coupon_amount: 0, // 优惠券优
            point_amount: 0, // 积分优惠
            total_discount_amount: 0, // 合计优惠
            // discount_amount_count: this.currentDiscount && this.currentPercentDiscount ? this.currentDiscount.disTotalAmount + this.currentPercentDiscount.disTotalAmount : this.currentDiscount.disTotalAmount || this.currentPercentDiscount.disTotalAmount || 0
        };
        const list = this.state.currentList;
        console.log(JSON.stringify(list));
        list.forEach((item, index) => {
            disForm.itemTotalAmount += Number(item.itemTotalAmount);
            disForm.num += Number(item.num);
            disForm.total_amount += Number((item.subtotal * 100).toFixed(2));
            disForm.discount_amount += Math.signFigures(item.base_goods.market_price * 100 * item.num) - Math.signFigures(item.subtotal * 100);
            // 能使用积分的商品总额为每个能使用积分的商品之和
            if (item.point_deduction) {
                console.log('未使用优惠券前', item.used_point_total);
                disForm.used_point_total_amount += item.used_point_total;
            }
        });
        // disForm.discount_amount += this.currentPercentDiscount ? this.currentPercentDiscount.disTotalAmount : 0;
        disForm.pay_amount =  disForm.total_amount  - disForm.coupon_amount - disForm.point_amount;   // 实付金额


        console.log('实际支付金额', disForm.pay_amount);
        memberState.couponList.forEach((item, index) => {
            const amount = item.discount.rule_type.amount;
            const type = item.discount.action_type.type;
            // 满足条件并且是满减订单
            if (disForm.pay_amount >= amount && type == 'cash') {
                userCoupon.push(item)
            }
        });
        this.setState({
            disForm: disForm,
            currentCouponList: userCoupon,
        }, () => {
            console.log('可以优惠券列表', userCoupon);
        });
        if (!this.state.currentCoupon || (this.state.currentCoupon && this.state.currentCoupon.discount.rule_type.amount > disForm.pay_amount)) {
            this.currentCoupon = userCoupon[0];
            this.setState({
                currentCoupon: userCoupon[0]
            })
        }

        // 优惠券
        if (this.currentCoupon) {
            disForm.used_point_total_amount = 0;
            // 优惠券能抵扣的金额
            let discount_money = Number((this.currentCoupon.discount.action_type.value * 100).toFixed(2));  // 将单位变成分

            // 如果是满减订单
            if(this.currentCoupon.discount.action_type.type == 'cash'){
                // 如果优惠券减掉的金额大于实际支付金额
                if (discount_money > disForm.pay_amount) {
                    // 优惠券优惠金额等于优惠券抵扣金额
                    discount_money = disForm.pay_amount;
                }
                disForm.coupon_amount = discount_money;
                disForm.coupon_id = this.currentCoupon.id;

                disForm.pay_amount = disForm.pay_amount - discount_money;
                disForm.pay_amount =  disForm.total_amount  - discount_money - disForm.point_amount;   // 实付金额
                if ( disForm.pay_amount <= 0){
                    disForm.pay_amount = 0
                }
                // 计算优惠金额分摊到每个商品上的金额
                list.forEach(item => {
                    // 应该减去促销抵扣的金额(重要)
                    const subtotal = Math.signFigures(item.subtotal *100) - item.goodsDisAmount;
                    const total_amount = disForm.total_amount;
                    if (item.point_deduction) {
                        // 重新计算每个能使用积分的金额
                        let used_point_total = item.used_point_total;
                        // 如果平摊到商品上的价格大于本身的价格，那平摊的价格就等于自身价格
                        if (subtotal / total_amount * discount_money > subtotal) {
                            used_point_total = subtotal
                        } else {
                            used_point_total = subtotal - Number((subtotal / total_amount * discount_money).toFixed(2))
                        }
                        console.log('分摊后的价格', used_point_total);
                        item.used_point_total = used_point_total;
                    }
                    // 使用优惠券后重新计算能使用积分的商品总额
                    if (item.point_deduction) {
                        console.log('使用优惠券后', item.used_point_total);
                        disForm.used_point_total_amount += item.used_point_total
                    }
                })
            } else {
                Tips.showFail('优惠券类型错误');
            }
        } else {
            // 将优惠信息还原
            disForm.coupon_amount = 0;
            disForm.coupon_id = 0;
            list.forEach(item => {
                if (item.point_deduction) {
                    item.used_point_total = Math.signFigures(item.subtotal *100) - item.goodsDisAmount
                }
            });
            disForm.pay_amount =  disForm.total_amount  - disForm.coupon_amount - disForm.point_amount;   // 实付金额
        }

        // 积分
        if (storeState.pointProportion && this.state.currentUser && this.state.pointStatus) {
            let  proportion = (storeState.pointProportion.point_order_limit / 100).toFixed(2); // 抵扣比例
            let used_point_total_amount = (disForm.used_point_total_amount).toFixed(0);  // 将有小数的分变为没有小数的分
            // 当前订单最多能抵扣多少钱
            let point_limit = Number(Math.signFigures(proportion * used_point_total_amount).toFixed(0));
            // 当前能用多少积分
            let current_point = Number(Math.min((point_limit * storeState.pointProportion.point_proportion).toFixed(2), this.state.currentUser.point));

            // 当前积分能抵扣多少钱
            let point_money = Number(Math.signFigures(this.state.currentUser.point * storeState.pointProportion.point_proportion)).toFixed(0);

            let point_amount = Math.min(point_limit, point_money);

            disForm.point_amount = Number((Math.floor(point_amount / 100) * 100).toFixed(0));
            disForm.used_point = Math.signFigures(disForm.point_amount / storeState.pointProportion.point_proportion)




            /!*disForm.used_point = Number((Math.floor(current_point / storeState.pointProportion.point_proportion) * storeState.pointProportion.point_proportion).toFixed(0));
            disForm.point_amount = Number(Math.signFigures(disForm.used_point * storeState.pointProportion.point_proportion));*!/
            // disForm.point_amount = Math.min(point_limit, point_money);
            /!* disForm.point_amount = 600;
             disForm.used_point = 30;*!/


            console.log(point_limit,current_point,point_money, point_amount, disForm);
            console.log('抵扣比例', proportion);
            console.log('当前能用多少积分', current_point);
            console.log('当前订单最多抵扣多少钱', storeState.pointProportion.point_proportion);
            console.log('当前有多少钱可以用来抵扣积分', disForm.point_amount)
        } else {
            disForm.used_point = 0;
            disForm.point_amount = 0;
            disForm.used_point_total_amount = 0;
        }

        console.log('能用来抵扣积分的金额', disForm.used_point_total_amount);
        let disTotalAmount = this.state.currentDiscount ? this.state.currentDiscount.disTotalAmount : 0;


        console.log('这个是正数嘛?', this.state.currentDiscount, disTotalAmount);
        disForm.pay_amount =  disForm.total_amount  - disForm.coupon_amount - disForm.point_amount - disTotalAmount;   // 实付金额
        disForm.total_discount_amount =  disForm.coupon_amount + disForm.point_amount + disTotalAmount;
        this.setState({
            disForm: disForm,
            currentList: list
        }, () => {
            console.log('这个是处理后的数据', this.state.currentList);
            console.log('这个是折扣数据', disForm);
        });*/

        // console.log('没有到这里来');
    }

    // 提交售后
    _submitOrder() {
        let {storeAction} = this.props;
        this.state.currentList.forEach(item => {
            item.user_discount = item.user_discount ? item.user_discount : 0;
            item.discount_price = item.discount_price ? item.discount_price : 0;
            item.subtotal_cent = Number((item.subtotal * 100).toFixed(2))
        });

        let data = {
            order_no: this.state.order_no,
            refund: {
                refund_amount: this.state.disForm.refund_amount,
                refund_items: [],
                content: this.state.refundContent ? this.state.refundContent.value : ''
            },
            order: {
                order_items: this.state.currentList || [],
                pay_amount: this.state.disForm.total_amount || 0
            }
        };

        this.state.refundGoods.forEach(item => {
            data.refund.refund_items.push({
                order_item_id: item.id,
                quantity: item.num
            })
        });
        console.log(data);
        storeAction.submitRefund(data, (res) => {
            if (res && res.status && res.data) {
                if (res.data.difference > 0) {
                    Actions.push('CashMoneyPage');
                } else {
                    Actions.push('CashExchange');
                }
            }
        });
    }

    // 取消
    _back() {
        Actions.pop();
    }

    // 切换问题描述
    _onSelect(index, value) {
        this.setState({
            refundContent: value
        })
    }



    // 点击尺码，更改sku
    _changeSku(id, index) {
        let {storeAction, storeState} = this.props;
        storeAction.getGoodsSku(id, (res) => {
            const item = this.state.currentList[index];
            this.setState({
                currentEditGoods: item,
                select_count: item.num,
                currentEditIndex: index
            });
            if (res.status) {
                this._specStore();
            }
        });
    }

    // 确认修改商品
    _modify() {
        if (this.state.canBuy) return;
        const list = this.state.currentList;
        const currentEditGoods = this.state.currentEditGoods;
        console.log(this.state.select_product, currentEditGoods);
        currentEditGoods.num = this.state.select_count;
        currentEditGoods.store_nums = this.state.store_count;
        currentEditGoods.spec_text = [
            this.state.select_product.color,
            this.state.select_product.size
        ];
        currentEditGoods.base_goods.market_price = fen_to_yuan(this.state.price);
        currentEditGoods.base_product.sku = this.state.select_product.sku;
        currentEditGoods.id = this.state.select_product.id;

        list[this.state.currentEditIndex] = currentEditGoods;
        this.setState({
            currentList: list
        }, () => {
            this.filterDis();
        });
        // this._checkSubtotal(false, this.state.currentEditIndex);

        this.refs.leftSkuModal.close();

    }

    // 删除订单
    _deleteOrder(index) {
        const list = this.state.handList;
        list.splice(index, 1);
        // 将挂起订单缓存
        storage.save({
            key: 'goods-handList',
            data: list
        });
        this.setState({
            handList: list
        });
    }
    // 处理SKU相关S
    // 处理SKU
    _selectSpec(spec) {
        let {storeState} = this.props;

        // 如果没有库存，直接return
        if (spec.disabled) {
            return
        }

        if (!spec.active) {
            for (let item of storeState.skuInfo[spec.index].values) {
                if (item.active) {
                    item.active = false;
                    break;
                }
            }
        }
        spec.active = !spec.active;
        storeState.skuInfo[spec.index].select = spec.active ? spec.id : '';
        this._specStore(this.result, spec.index)
    }

    // 处理库存
    _specStore(result, key) {
        let {storeState} = this.props;

        result = result || storeState.specStore;

        this.result = result;

        const data = result.data;

        if (key === undefined) {
            storeState.skuInfo.forEach(spec => {
                for (let v of spec.values) {
                    v.disabled = !data[v.id] || data[v.id].count == 0;
                }
            });

            this.skuTable = result.table;

            const canBuy = this._disallow_cart();

            console.log('这个是啥呀',canBuy);
            this.setState({
                canBuy: canBuy
            });

            storeState.skuInfo.forEach(spec => {
                if (!spec.select) {
                    for (let v of spec.values) {
                        if (!v.disabled && data[v.id] && data[v.id].count) {
                            v.active = true;
                            spec.select = v.id;

                            const canBuy = this._disallow_cart();
                            console.log('这个是啥呀',canBuy);
                            this.setState({
                                canBuy: canBuy
                            });

                            this._specStore(result, v.index);

                            return
                        }
                    }
                }
            });

            return
        }

        const spec = storeState.skuInfo[key];

        if (spec.select) {
            console.log(data, spec.select);
            this.setState({
                store_count: data[spec.select].count
            });


            for (let i = 0; i < storeState.skuInfo.length; i++) {
                if (i === key) continue;

                let s = storeState.skuInfo[i];

                s.values.forEach(v => {
                    v.disabled = !data[spec.select].specs[v.id].count;
                });

                if (s.select) {
                    this.setState({
                        store_count: data[spec.select].specs[s.select].count
                    });
                }
            }
        } else {
            this.setState({
                store_count: 0
            });

            for (let i = 0; i < storeState.skuInfo.length; i++) {
                if (i === key) continue;

                let s = storeState.skuInfo[i];

                s.values.forEach(v => {
                    v.disabled = !data[v.id] || !data[v.id].count;
                });

                if (s.select) {
                    this.setState({
                        store_count: data[s.select].count
                    })
                }
            }
        }

        const canBuy = this._disallow_cart();
        console.log('这个是啥呀',canBuy);
        this.setState({
            canBuy: canBuy
        });

        console.log(this.state.store_count, this.store_count);
    }


    // 处理价格
    _disallow_cart() {
        let {storeState} = this.props;
        if (!storeState.skuInfo.length) {
            return !this.state.store_count;
        }

        var ids = [], select_product= {};
        for (let spec of storeState.skuInfo) {
            if (!spec.select) {
                this.setState({
                    price: Math.signFigures(this.state.currentEditGoods.base_goods.market_price * 100),
                    select_product: null
                });
                return true
            }
            ids.push(spec.select);

            for (let v of spec.values) {
                if (v.id === spec.select) {
                    switch (spec.label_key) {
                        case 'color':
                            select_product.img = v.img;
                            select_product.color = v.alias || v.value;
                            break;
                        default:
                            select_product.size = v.alias || v.value;
                    }
                    break;
                }
            }
        }

        if (this.skuTable) {
            ids = ids.sort((a, b) => a > b).join('-');
            select_product = Object.assign(select_product, this.skuTable[ids]);
        }

        this.setState({
            price: Math.signFigures(select_product.price * 100),
            select_product: select_product
        }, () => {
            this.refs.leftSkuModal.open();

        });

        console.log('这个是选中的', select_product);



        return false
    }


    // 处理选择数量
    _changeEditGoodsNum(num) {
        const val = Number(this.state.select_count) + (num ? 1: -1);
        if (val > 0 && val <= this.state.store_count) {
            this.setState({
                select_count: val
            })
        } else {
            ToastAndroid.showWithGravity('库存不足', ToastAndroid.SHORT, ToastAndroid.CENTER)
        }
    }

    // 处理SKU相关E









    _closeSearchModal() {
        this.refs.searchModal.close();
    }
    _clearSearchText() {
        this.setState({
            searchText: ''
        })
    }

    // 申请商品列表渲染
    _applyRenderRow(rowData, index) {
        return (
            <View style={[style.tableTitle, style.tableTitleBorder, style.whiteTitle]}>
                <View style={[style.tableTitleText, {flex: 2, flexDirection: 'row', alignItems: 'center',}]} onPress={() => this._changeSku(rowData.o2o_goods_id, index)}>
                    <Text>{rowData.item_name}</Text>
                </View>
                <Text style={[style.tableTitleText]}>{fen_to_yuan(rowData.unit_price)}</Text>
                <Text style={[style.tableTitleText]}>{rowData.quantity}</Text>
                <Text style={style.tableTitleText}>¥ {fen_to_yuan(rowData.total)}</Text>
                <View style={[style.tableTitleText,{flex: 0.5}]}>
                    <View style={style.tableInput}>
                        <TouchableOpacity
                            onPress={() => this._changeRefundListNum(String(Number(this.state.refundGoods[index].num) - 1), index)}
                        >
                            <Text style={[style.inputCut, {textAlign: 'center', fontSize: 20}]}>
                                一
                            </Text>
                        </TouchableOpacity>
                        <TextInput style={style.textInput}
                                   keyboardType='numeric'
                                   onChangeText={(text) => this._changeRefundListNum(text, index)}
                                   value={String(rowData.num)}
                        >
                        </TextInput>
                        <TouchableOpacity
                            onPress={() => this._changeRefundListNum(String(Number(this.state.refundGoods[index].num) + 1), index)}

                        >
                            <Text style={[style.inputAdd, {textAlign: 'center', fontSize: 20}]}>
                                +
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
            </View>
        )

    }

    // 换货商品列表渲染
    _renderRow(rowData, index) {
        return (
            <View style={[style.tableTitle, style.tableTitleBorder, style.whiteTitle]}>
                <View style={[style.tableTitleText, {flex: 1.5, flexDirection: 'row', alignItems: 'center',}]} onPress={() => this._changeSku(rowData.o2o_goods_id, index)}>
                    <Text>{rowData.base_goods.goods_no} </Text>
                    {/*{this._disText(rowData)}*/}
                </View>
                <Text style={[style.tableTitleText, {flex: 1.5}]} onPress={() => this._changeSku(rowData.o2o_goods_id, index)}>{rowData.base_goods.name}</Text>
                <Text style={style.tableTitleText} onPress={() => this._changeSku(rowData.o2o_goods_id, index)}>{rowData.spec_text.join(',')}</Text>
                <Text style={style.tableTitleText} onPress={() => this._changeSku(rowData.o2o_goods_id, index)}>¥ {rowData.base_goods.market_price}</Text>
                <View style={[style.discountInputWarp]}>
                    <View style={[style.discountInputBox, rowData.can_change_discount ? style.discountInputBorder : '']}>
                        <TextInput
                            style={[style.discountInput, rowData.can_change_discount ? '' : style.widthAuto]}
                            keyboardType='numeric'
                            value={String(rowData.user_discount)}
                            onChangeText={(text) => this._changeDiscount(index, 'proportion', text)}
                            editable={rowData.can_change_discount ? true : false}
                            onBlur={() => this._inputBlur(index)}
                        >
                        </TextInput>
                        <Text>
                            %
                        </Text>
                    </View>
                </View>
                <View style={[style.discountInputWarp]}>
                    <View style={[style.discountInputBox, rowData.can_change_discount ? style.discountInputBorder : '']}>
                        <Text style={{marginTop: -2}}>
                            ￥
                        </Text>
                        <TextInput
                            style={[style.discountInput, rowData.can_change_discount ? '' : style.widthAuto]}
                            keyboardType='numeric'
                            editable={rowData.can_change_discount ? true : false}
                            onChangeText={(text) => this._changeDiscount(index, 'money', text)}
                            value={String(rowData.discount_price)}
                            onBlur={() => this._inputBlur(index)}
                        >
                        </TextInput>
                    </View>
                </View>
                <View style={[style.tableTitleText,{flex: 1}]}>
                    <View style={style.tableInput}>
                        <TouchableOpacity
                            onPress={() => this._changeListNum(String(Number(this.state.currentList[index].num) - 1), index)}
                        >
                            <Text style={[style.inputCut, {textAlign: 'center', fontSize: 20}]}>
                                一
                            </Text>
                        </TouchableOpacity>
                        <TextInput style={style.textInput}
                                   keyboardType='numeric'
                                   onChangeText={(text) => this._changeListNum(text, index)}
                                   value={String(rowData.num)}
                        >
                        </TextInput>
                        <TouchableOpacity
                            onPress={() => this._changeListNum(String(Number(this.state.currentList[index].num) + 1), index)}

                        >
                            <Text style={[style.inputAdd, {textAlign: 'center', fontSize: 20}]}>
                                +
                            </Text>
                        </TouchableOpacity>
                    </View>
                </View>
                <Text style={[style.tableTitleText, {textAlign: 'center'}]}>¥ {rowData.subtotal}</Text>
                <View style={[style.tableTitleText, {alignItems: 'center'}]}>
                    <TouchableOpacity
                        style={{width: '100%',alignItems: 'center'}}
                        onPress={() => this._deleteListItem(index)}
                    >
                        <Text style={style.inputDelete}>
                            一
                        </Text>
                    </TouchableOpacity>
                </View>
            </View>
        )

    }


    // 问题描述渲染
    _problemRow() {
        if (this.state.refundInfo && this.state.refundInfo.reasons) {
            return this.state.refundInfo.reasons.map((item, index) => {
                console.log(item);
                return (
                    <RadioButton style={style.radioButton} value={item} key={index}>
                        <Text style={style.radioButtonText}>
                            {item.value}
                        </Text>
                    </RadioButton>
                )
            })
        }
    }


    // 搜索商品列表渲染
    _renderSearchRow(rowData, index) {
        return (
            <View style={style.goodsItemBox}>
                <TouchableWithoutFeedback onPress={() => this._addGoods(rowData, rowData.store_nums)}>
                    <View style={[style.goodsItem, !rowData.store_nums&&style.dashed]}>
                        <Text style={style.goodsNo}>
                            {rowData.base_goods.goods_no}
                        </Text>
                        <Text style={style.goodsNames}>
                            {rowData.base_goods.name}
                        </Text>
                        <Text style={[style.goodsNames, style.bigSizeType]}>
                            {rowData.spec_text.join('，')}
                        </Text>
                        <View style={style.goodsNum}>
                            <Text style={{flex: 1}}>
                                ￥ {rowData.base_goods.market_price}
                            </Text>
                            <Text>
                                库存： {rowData.store_nums}
                            </Text>
                        </View>
                    </View>
                </TouchableWithoutFeedback>
            </View>
        )
    }




    _disText(data) {
        if (this.currentPercentDiscount) {
            let id = this.currentPercentDiscount.id;
            let discount_ids = data.discount_ids;
            if (discount_ids.indexOf(id) != -1) {
                return (
                    <Text style={style.disClass}>折</Text>
                )
            } else {
                return
            }
        } else {
            return
        }
    }

    // sku渲染
    _renderSkuRow(rowData) {
        console.log('这个是获取到的sku信息', rowData);
        if (rowData && rowData.length && this.state.currentEditGoods.base_goods) {
            return (
                <View>
                    <Modal
                        ref={"leftSkuModal"}
                        position="top"
                        style={{backgroundColor:'transparent', alignItems: 'flex-end'}}
                        coverScreen={true}
                        // backdropPressToClose={false}
                        swipeToClose={false}
                    >
                        <View style={style.leftModalBox}>
                            <View style={style.imgBox}>
                                <Image style={style.goodsImg} source={{uri: 'http://pic30.nipic.com/20130613/12074212_110133058344_2.jpg'}}></Image>
                                <View style={style.goodsName}>
                                    <View>
                                        <Text style={style.goodsText}>
                                            {this.state.currentEditGoods.base_goods.goods_no}
                                        </Text>
                                        <Text style={style.goodsText}>
                                            {this.state.currentEditGoods.base_goods.name}
                                        </Text>
                                    </View>

                                    <Text style={style.goodsMoney}>
                                        ￥ {fen_to_yuan(this.state.price)}
                                    </Text>
                                </View>
                                <View style={style.closeIcon}>
                                    <TouchableWithoutFeedback >
                                        <CXIcon name='guanbi' color='#909090' size={30}>

                                        </CXIcon>
                                    </TouchableWithoutFeedback>
                                </View>

                            </View>
                            <View style={style.skuBox}>
                                {
                                    rowData.map((spec, index) => {
                                        return (
                                            <View style={style.specLine} key={index}>
                                                <View>
                                                    <Text style={style.specTitle}>
                                                        {spec.label || spec.label_key}
                                                    </Text>
                                                </View>
                                                <View style={style.specValueBox}>
                                                    {spec.values.map((item, index) => {
                                                        return (
                                                            <Text key={index} onPress={() => this._selectSpec(item)} style={[style.specValue, item.active && !item.disabled ? style.specValueActive : '', item.disabled && !item.active ? style.specValueDisable : '']}>
                                                                {item.alias || item.value}
                                                            </Text>
                                                        )
                                                    })}
                                                </View>
                                            </View>
                                        )
                                    })
                                }
                            </View>
                            <View style={style.skuNumBox}>
                                <View style={style.skuNumInputBox}>
                                    <Text style={style.skuNumAction} onPress={() => this._changeEditGoodsNum(0)}>
                                        一
                                    </Text>
                                    <Text style={{width: 70, height: 50, lineHeight: 50, textAlign: 'center', backgroundColor: white}}>
                                        {this.state.select_count}
                                    </Text>
                                    <Text style={[style.skuNumAction]} onPress={() => this._changeEditGoodsNum(1)}>
                                        +
                                    </Text>
                                </View>
                                <Text style={{color: white, marginLeft: 35, flex: 1}}>
                                    库存: {this.state.store_count}件
                                </Text>
                                <TouchableWithoutFeedback onPress={() => this._modify()}>
                                    <View style={[style.skuChangeBox, !this.state.canBuy ? '' : style.skuChangeBoxDis ]}>
                                        <Text style={[{marginRight: 25, color: white}]}>
                                            修改
                                        </Text>
                                        <Text style={[{color: white}]}>
                                            ￥ {fen_to_yuan((this.state.price * this.state.select_count))}
                                        </Text>
                                    </View>
                                </TouchableWithoutFeedback>
                            </View>
                        </View>
                    </Modal>
                </View>
            )
        }
    }

    render() {
        let {storeState, memberState} = this.props;
        return (
            <View style={style.bodyBox}>
                <StatusBar hidden={true} />
                {/*顶部导航*/}
                {/*选择部分*/}
                {/*<View style={style.operatingBox}>
                    <View style={[style.operatingItem, {flex: 1}]}>
                        <TextInput style={style.operatingInput}
                                   placeholder='请输入需要搜索商品的信息'
                                   blurOnSubmit={true}
                                   onChangeText={(text) => this.setState({searchText: text})}
                                   value={this.state.searchText}
                        >

                        </TextInput>

                        <View style={[style.closeIcon, {right: 105, top: 10}]}>
                            <TouchableWithoutFeedback onPress={() => this._clearSearchText()}>
                                <View>
                                    <CXIcon name='guanbi' color='#909090' size={30}>

                                    </CXIcon>
                                </View>
                            </TouchableWithoutFeedback>
                        </View>
                        <Text onPress={() => this._searchGoods()} style={style.searchText}>搜索</Text>
                    </View>
                    <TouchableWithoutFeedback onPress={() => this._getUserList()}>
                        <View style={style.operatingItem}>
                            <Text style={style.userText}>
                                会员信息：
                            </Text>

                            {this._selectUserNode(this.state.currentUser)}

                        </View>
                    </TouchableWithoutFeedback>

                    <View style={[style.operatingItem, {flex: 1.4}]}>
                        {this._selectDiscountNode()}
                        {this._selectCouponNode()}
                        {this._selectPointNode()}
                    </View>
                </View>*/}

                <View style={style.returnList}>
                    <ScrollView>
                        {/*退货表格部分*/}
                        <View style={style.tableBox}>
                            {/*表格头部*/}
                            <View style={style.tableTitle}>
                                <Text style={[style.tableTitleText,{flex: 2}]}>申请售后商品</Text>
                                <Text style={[style.tableTitleText]}>单价</Text>
                                <Text style={[style.tableTitleText]}>购买数量</Text>
                                <Text style={style.tableTitleText}>实付金额</Text>
                                <Text style={[style.tableTitleText, {flex: 0.5}]}>申请数量</Text>
                            </View>
                            {/*表格身体*/}
                            <FlatList
                                extraData={this.state}
                                keyExtractor={(item, index) => index.toString()}
                                data={this.state.refundGoods}
                                renderItem={({item, index}) => this._applyRenderRow(item, index)}
                            >

                            </FlatList>
                        </View>

                        {/*换货表格部分*/}
                        <View style={style.tableBox}>
                            {/*表格头部*/}
                            <View style={style.tableTitle}>
                                <Text style={[style.tableTitleText, {flex: 1.5}]}>货号</Text>
                                <Text style={[style.tableTitleText, {flex: 1.5}]}>品名</Text>
                                <Text style={style.tableTitleText}>尺码</Text>
                                <Text style={style.tableTitleText}>单价</Text>
                                <Text style={[style.tableTitleText]}>折扣</Text>
                                <Text style={[style.tableTitleText]}>折后价</Text>
                                <Text style={[style.tableTitleText, {flex: 1, textAlign: 'center'}]}>数量</Text>
                                <Text style={[style.tableTitleText, {textAlign: 'center'}]}>小计</Text>
                                <Text style={[style.tableTitleText, {textAlign: 'center'}]}>删除</Text>
                            </View>
                            {/*表格身体*/}
                            <FlatList
                            extraData={this.state}
                            keyExtractor={(item, index) => index.toString()}
                            data={this.state.currentList}
                            renderItem={({item, index}) => this._renderRow(item, index)}
                        >

                        </FlatList>
                        </View>

                        {/*添加换货商品*/}
                        <View style={style.addRefundBox}>
                            <View style={{flex: 1}}>
                                <Text style={style.addRefundBtn} onPress={() =>  this.refs.searchModal.open()}>
                                    添加商品
                                </Text>
                            </View>
                            <View style={style.numBox}>
                                <Text style={{marginRight: 100}}>
                                    数量： {this.state.disForm.num || 0}
                                </Text>
                                <Text style={{marginRight: 100}}>
                                    总额：{this.state.disForm.itemTotalAmount || 0}
                                </Text>
                                <Text style={{marginRight: 100}}>
                                    会员折扣优惠：{fen_to_yuan(this.state.disForm.discount_amount) || 0}
                                </Text>
                                <Text>
                                    合计：￥{fen_to_yuan(this.state.disForm.total_amount) || '0.00'}
                                </Text>
                            </View>
                        </View>

                        {/*问题描述*/}
                        <View style={style.problemBox}>
                            <Text style={style.problemTitle}>
                                问题描述
                            </Text>
                            <View>
                                <RadioGroup selectedIndex={0} style={style.radioGroup} color={mainBackgroundColor} onSelect={(index, value) => this._onSelect(index, value)}>
                                    {this._problemRow()}
                                </RadioGroup>
                            </View>
                        </View>
                    </ScrollView>
                </View>



                {/*底部操作部分*/}
                <View style={style.bottomOperating}>
                    <View style={style.disInfoBox}>
                        <View style={style.disInfoItem}>
                            <Text style={style.itemText}>
                                退款金额
                            </Text>
                            <Text style={style.itemText}>
                                {fen_to_yuan(this.state.disForm.refund_amount) || 0}
                            </Text>
                        </View>
                        <View style={style.disInfoItem}>
                            <Text style={style.itemText}>
                                换货金额
                            </Text>
                            <Text style={style.itemText}>
                                {fen_to_yuan(this.state.disForm.total_amount) || 0}
                            </Text>
                        </View>
                        <View style={[style.disInfoItem, {borderRightWidth: 0}]}>
                            <Text style={style.itemText}>
                                订单差价
                            </Text>
                            <Text style={style.itemText}>
                                {fen_to_yuan(this.state.disForm.spread_amount) || 0}
                            </Text>
                        </View>
                    </View>

                    <View style={style.clearBox}>
                        <TouchableOpacity onPress={() => this._back()}>
                            <View style={style.clearBtn}>
                                <Text style={{color: white, fontSize: 18}}>
                                    取消
                                </Text>
                            </View>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this._submitOrder()}>
                            <View style={[style.submitBtn]}>
                                <Text style={{color: white, fontSize: 18}}>
                                    <Text>
                                        确定
                                    </Text>
                                    <Text>
                                        ￥ {(fen_to_yuan(this.state.disForm.spread_amount)) || 0}
                                    </Text>
                                </Text>
                            </View>
                        </TouchableOpacity>
                    </View>
                </View>

                {/*搜索结果弹窗*/}
                <View style={{height: 720}}>
                    <Modal
                        ref={"searchModal"}
                        position="center"
                        style={{backgroundColor:'transparent', width: 900, justifyContent:'center'}}
                        coverScreen={true}
                        swipeArea={280}
                        // backdropPressToClose={false}
                        swipeToClose={false}
                    >
                        <View style={style.searchModalBox}>
                            <View style={style.searchTitle}>
                                <Text>
                                    搜索结果
                                </Text>
                                <View style={[style.closeIcon, {right: 0, top: 0}]}>
                                    <TouchableWithoutFeedback onPress={() => this._closeSearchModal()}>
                                        <View>
                                            <CXIcon name='guanbi' color='#909090' size={30}>

                                            </CXIcon>
                                        </View>
                                    </TouchableWithoutFeedback>
                                </View>
                            </View>
                            <View style={style.searchInputBox}>
                                <View style={{flex: 1}}>
                                    <TextInput
                                        style={style.searchInput}
                                        onChangeText={(text) => this.setState({searchText: text})}
                                        value={this.state.searchText}
                                    >

                                    </TextInput>
                                </View>
                                <View style={[style.closeIcon, {right: 160, top: 28}]}>
                                    <TouchableWithoutFeedback onPress={() => this._clearSearchText()}>
                                        <View>
                                            <CXIcon name='guanbi' color='#909090' size={30}>

                                            </CXIcon>
                                        </View>
                                    </TouchableWithoutFeedback>
                                </View>
                                <Text style={[style.searchBtn, style.textWhite]} onPress={() => this._searchGoods()}>
                                    搜索
                                </Text>
                            </View>
                            <View style={style.searchGoods}>

                                <FlatList
                                    style={style.searchScrollView}
                                    numColumns={3}
                                    columnWrapperStyle={{flexDirection: 'row'}}
                                    extraData={storeState.searchGoodsList}
                                    keyExtractor={(item, index) => index.toString()}
                                    data={storeState.searchGoodsList}
                                    renderItem={({item, index}) => this._renderSearchRow(item, index)}
                                >

                                </FlatList>
                            </View>
                        </View>
                    </Modal>
                </View>
                {/*左侧SKU弹出*/}
                {this._renderSkuRow(storeState.skuInfo)}
            </View>
        )
    }
}

const style = StyleSheet.create({
    bodyBox: {
      height: '100%'
    },
    operatingBox: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 80,
        backgroundColor: '#F3F3F3'
    },
    operatingItem: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        textAlign: 'center',
        borderRightWidth: 1,
        borderRightColor: '#D8D8D8',
        paddingLeft: 25,
        paddingRight: 25
    },
    operatingInput: {
        paddingLeft: 20,
        width: '80%',
        height: 50,
        backgroundColor: '#fff',
        borderTopLeftRadius: 4,
        borderBottomLeftRadius: 4
    },
    userText: {
        width: '20%',
        color: '#4A4A4A',
    },
    userInfoInput: {

        flexDirection: 'row',
        alignItems: 'center',

        paddingLeft: 25,
        width: '80%',
        height: 50,
        backgroundColor: '#ffffff',
        color: '#909090'
    },
    userInfo: {

    },
    searchText: {
        width: '20%',
        height: 50,
        lineHeight: 50,
        textAlign: 'center',
        backgroundColor: mainBackgroundColor,
        color: white,
        borderTopRightRadius: 4,
        borderBottomRightRadius: 4
    },
    disBox: {
        flexDirection: 'column',
        flex: 1,
        borderWidth: 1,
        borderColor: '#909090',
        padding: 5,
        borderRadius: 1,
        marginRight: 30,

    },
    disTitle: {

    },
    redColor: {
        color: mainBackgroundColor
    },
    disText: {
        marginTop: 5,
        color: '#909090',
        fontSize: 12,
    },
    textWhite: {
        color: white
    },
    tableBox: {


    },
    tableTitle: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingTop: 15,
        paddingBottom: 15,
        paddingLeft: 25,
        paddingRight: 25,
    },
    whiteTitle: {
        backgroundColor: white
    },

    tableTitleBorder: {
        borderBottomWidth:1,
        borderBottomColor: '#F0F0F5',
    },
    tableTitleText: {
        // textAlign: 'center',
        flex: 1,
        paddingRight: 50,
        color: '#666666'
    },
    discountInputWarp: {
        flexDirection: 'row',
        alignItems: 'center',
        flex: 1,
        paddingRight: 50,
    },
    discountInputBox: {
        flexDirection: 'row',
        alignItems: 'center',
        // justifyContent: 'center',
        // width: 70,
        height: 30,
        paddingHorizontal: 5,
    },
    discountInput: {
        width: 60,
        height: 50,
        color: '#4A4A4A',
        // borderWidth: 1
    },
    discountInputBorder: {
        borderWidth: 1,
        borderColor: '#D7D7D7',
    },
    widthAuto: {
        width: 'auto'
    },
    tableInput: {
        height: 30,
        borderWidth: 1,
        borderColor: '#D7D7D7',
        flexDirection: 'row',
        alignItems: 'center',
        borderRadius: 1,
    },
    inputAdd: {
        height: 30,
        lineHeight: 30,
        width: 30,
        borderLeftWidth: 1,
        borderLeftColor: '#D7D7D7',

    },
    textInput: {
        textAlign: 'center',
        height: 50,
        flex: 1,
        color: '#4A4A4A',
    },
    inputCut: {
        height: 30,
        lineHeight: 30,
        width: 30,
        borderRightWidth: 1,
        borderRightColor: '#D7D7D7'
    },
    inputDelete: {
        width: 20,
        height: 20,
        lineHeight: 20,
        backgroundColor: mainBackgroundColor,
        color: white,
        borderRadius: 20,
        textAlign: 'center',
        marginVertical: 10
    },
    scrollView: {
        height: 396,
    },
    addRefundBox: {
        flexDirection: 'row',
        alignItems: 'center',
        height: 85,
        backgroundColor: '#ffffff',
        paddingLeft: 25,
        borderBottomWidth: 1,
        borderBottomColor: '#F0F0F5',
    },
    addRefundBtn: {
        color: mainBackgroundColor,
        borderWidth: 1,
        borderColor: mainBackgroundColor,
        borderRadius: 4,
        width: 100,
        textAlign: 'center',
        height: 40,
        lineHeight: 40
    },
    numBox: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingRight: 80
    },
    bottomOperating: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        flexDirection: 'row',
        alignItems: 'center',
        height: 90,
        backgroundColor: '#202020',
        paddingLeft: 25,
        paddingRight: 25
    },
    disInfoBox: {
        // flex: 1,
        height: '100%',
        flexDirection: 'row',
        alignItems: 'center',
        backgroundColor: '#4A4A4A'
    },
    disInfoItem: {
        borderRightWidth: 1/PixelRatio.get(),
        borderRightColor: '#666666',
        paddingLeft: 30,
        paddingRight: 30,
        alignItems: 'center'
    },
    itemText: {
        color: white,
        marginBottom: 5
    },
    hang: {
        marginLeft: 30,
        backgroundColor: '#4B8AF2',
        width: 120,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 2
    },
    expand: {
        backgroundColor: '#202020',
        borderWidth: 1/PixelRatio.get(),
        borderColor: white,
    },
    dot: {
        position: 'absolute',
        right: -15,
        top: -15,
        width: 30,
        height: 30,
        textAlign: 'center',
        lineHeight: 28,
        backgroundColor: mainBackgroundColor,
        borderRadius: 30,
        color: '#fff'
    },
    clearBox: {
        flex: 1,
        flexDirection: 'row',
        justifyContent: 'flex-end',
        alignItems: 'center'
    },
    clearBtn: {
        marginRight: 30,
        backgroundColor: '#909090',
        width: 120,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 2
    },
    submitBtn: {
        backgroundColor: mainBackgroundColor,
        width: 200,
        height: 50,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 2
    },
    submitBtnDis: {
        backgroundColor: '#909090',
    },
    modalBox: {
        flex: 1,
        alignItems: 'center',
        backgroundColor: white,
    },
    modalContent: {
        borderRadius: 2,
        width: 660,
        backgroundColor: white
    },
    modalTitle: {
        textAlign: 'center',
        height: 60,
        lineHeight: 60,
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8'
    },
    modalBottom: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 90,
        borderTopWidth: 1,
        borderTopColor: '#DBDBDB'
    },
    modalClear: {
        width: 160,
        height: 44,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 4,
        backgroundColor: '#909090',
    },
    modalSubmit: {
        width: 160,
        height: 44,
        alignItems: 'center',
        justifyContent: 'center',
        borderRadius: 4,
        backgroundColor: mainBackgroundColor
    },
    modalBtnText: {
        color: white,
        fontSize: 18
    },
    label: {
        marginLeft: 100
    },
    btnName: {
        width: 100,
        marginLeft: 50,
        marginRight: 70
    },
    btnPrice: {
        color: mainBackgroundColor
    },
    btnNum: {
        width: 70,
        marginRight: 100
    },
    deleteBtn: {
        flex: 1,
        textAlign:'center',
    },
   /* radioButton: {
        height: 65,
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8',
        paddingLeft: 30,
        // marginLeft: 30,
        flexDirection: 'row',
        alignItems: 'center',
    },*/



    wrapper: {
        paddingTop: 50,
        flex: 1
    },

    modal: {
        justifyContent: 'center',
        alignItems: 'center'
    },

    modal2: {
        height: 230,
        backgroundColor: "#3B5998"
    },

    modal3: {
        height: 300,
        width: 300
    },

    modal4: {
        height: 300
    },

    btn: {
        margin: 10,
        backgroundColor: "#3B5998",
        color: "white",
        padding: 10
    },

    btnModal: {
        position: "absolute",
        top: 0,
        right: 0,
        width: 50,
        height: 50,
        backgroundColor: "transparent"
    },

    text: {
        color: "black",
        fontSize: 22
    },

    leftModalBox: {
        width: 875,
        height: '100%',
        paddingLeft: 30,
        paddingTop: 30,
        paddingRight: 30,
        backgroundColor: white
    },
    imgBox: {
        flexDirection: 'row',
    },
    goodsImg: {
        width: 200,
        height: 200,
        marginRight: 50
    },
    goodsName: {
        justifyContent: 'space-between'
    },
    goodsText: {
        fontSize: 24,
        color: '#202020'
    },
    goodsMoney: {
        fontSize: 28,
        color: mainBackgroundColor
    },
    skuBox: {
        backgroundColor: '#F3F3F3',
        paddingTop: 20,
        paddingLeft: 20,
        paddingRight: 20,
        marginTop: 20
    },
    specLine: {
        marginBottom: 10,
    },
    specTitle: {
        color: '#909090',
        marginBottom: 20
    },
    specValueBox: {
        flexDirection: 'row',
        alignItems: 'center',
        flexWrap: 'wrap'
    },
    specValue: {
        paddingTop: 12,
        paddingBottom: 12,
        paddingLeft: 30,
        paddingRight: 30,
        backgroundColor: white,
        borderRadius: 4,
        // borderWidth: 1,
        // borderColor: '#D7D7D7',
        color: '#4A4A4A',
        marginRight: 20,
        marginBottom: 10
    },
    specValueDisable: {
        backgroundColor: '#E8E7E7',
        color: '#9F9F9F'
    },
    specValueActive: {
        backgroundColor: mainBackgroundColor,
        // borderWidth: 1,
        // borderColor: mainBackgroundColor,
        color: white,
    },
    skuNumBox: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        flexDirection: 'row',
        alignItems: 'center',
        paddingLeft: 30,
        paddingRight: 30,
        height: 90,
        backgroundColor: '#202020',
    },
    skuNumInputBox: {
        flexDirection: 'row',
        alignItems: 'center',
        borderWidth: 1,
        height: 50,
        borderColor: '#D7D7D7'
    },

    skuNumAction: {
        textAlign: 'center',
        fontSize: 20,
        width: 50,
        lineHeight: 50,
        height: 50,
        backgroundColor: '#D7D7D7',
        color: '#4A4A4A'
    },
    skuChangeBox: {
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        color: white,
        backgroundColor: mainBackgroundColor,
        borderRadius: 4,
        height: 50,
        width: 200,
    },
    skuChangeBoxDis: {
        backgroundColor: '#D7D7D7',
    },
    closeIcon: {
        position: 'absolute',
        right: -30,
        top: -30,

    },
    couponUserName: {
        flexDirection: 'row',
        marginTop: 14
    },
    couponItemBox: {
        flexDirection: 'row',
        flexWrap: 'wrap'
    },
    couponTime: {
        fontSize: 10,
        color: '#4A4A4A',
        marginTop: 5
    },
    couponText: {
        color: '#909090',
        fontSize: 14,
        marginBottom: 20
    },
    couponItem: {
        width: '33%',
        backgroundColor: white,
        borderRadius: 4,
        paddingRight: 20,
        paddingLeft: 20,
        paddingTop: 10,
        paddingBottom: 10,
        marginRight: 20,
        marginBottom: 20
    },
    couponSubmitBox: {
        position: 'absolute',
        left: 0,
        right: 0,
        bottom: 0,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'flex-end',
        paddingLeft: 30,
        paddingRight: 30,
        height: 90,
        backgroundColor: '#202020',
    },
    couponSubmit: {
        paddingTop: 10,
        paddingBottom: 10,
        paddingLeft: 60,
        paddingRight: 60,
        color: white,
        borderRadius: 4,
        backgroundColor: mainBackgroundColor
    },
    couponItemActive: {
        backgroundColor: mainBackgroundColor
    },

    // 搜索弹窗部分
    searchModalBox: {

        /* position: 'absolute',
         top: 0,
         width: 900,
         flex: 1,*/
        // alignItems: 'center',
        backgroundColor: white,
        borderRadius: 4
    },
    searchTitle: {
        height: 60,
        justifyContent: 'center',
        paddingLeft: 30,
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8'
    },
    searchInputBox: {
        paddingHorizontal: 30,
        paddingVertical: 20,
        flexDirection: 'row',
        alignItems: 'center',
        borderBottomWidth: 1,
        borderBottomColor: '#D8D8D8',

    },
    searchBtn: {
        width: 120,
        height: 45,
        textAlign: 'center',
        lineHeight: 45,
        backgroundColor: mainBackgroundColor,
        borderTopRightRadius: 4,
        borderBottomRightRadius: 4
    },
    searchInput: {
        paddingLeft: 15,
        height: 45,
        backgroundColor: '#F3F3F3',
        borderTopLeftRadius: 4,
        borderBottomLeftRadius: 4
    },
    searchGoods: {
        paddingVertical: 30,
        paddingHorizontal: 10,
        // height: 280,

    },
    searchScrollView: {
        height: 280,
    },
    goodsItemBox: {
        width: '33%',
        marginBottom: 20,
        paddingHorizontal: 10
    },
    goodsItem: {
        padding: 10,
        backgroundColor: '#F3F3F3',
        borderWidth: 1,
        borderColor: '#D7D7D7',
        borderRadius: 4,
    },
    dashed: {
        borderStyle: 'dashed'
    },
    goodsNo: {
        fontSize: 16,
        color: '#4A4A4A',
        fontWeight: 'bold'
    },
    goodsNames: {
        fontSize: 12,
        color: '#4A4A4A',
        marginTop: 5
    },
    bigSizeType: {
        fontSize: 14,
        fontWeight: 'bold',
        color: mainBackgroundColor
    },
    goodsNum: {
        flexDirection: 'row',
        alignItems: 'center',
        marginTop: 5
    },

    // 会员列表部分
    listItem: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        paddingHorizontal: 20,
        borderBottomWidth: 1,
        borderColor: '#F0F0F5',
    },
    listItemText: {
        flex: 2,
        fontSize: 14,
        color: '#4A4A4A'
    },
    titleColor: {
        color: '#909090'
    },
    flex1: {
        flex: 1.5
    },
    disClass: {
        width: 25,
        height: 25,
        textAlign: 'center',
        lineHeight: 25,
        color: mainBackgroundColor,
        borderWidth: 1,
        borderColor: mainBackgroundColor
    },
    mainBorderColor: {
        borderColor: mainBackgroundColor
    },
    mainColor: {
        color: mainBackgroundColor
    },
    returnList: {
        /*flex: 1,
        paddingBottom: 80,*/
    },
    problemBox: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 15,
        paddingHorizontal: 20,
        backgroundColor: white,
        borderBottomWidth: 1,
        borderBottomColor: '#F0F0F5',
    },
    problemTitle: {
        color: '#909090',
        fontSize: 14,
        marginRight: 30
    },
    radioGroup: {
        flexDirection: 'row',
        alignItems: 'center'
    },
    radioButton: {
        marginRight: 30
    },
    radioButtonText: {
        color:'#232323',
        marginLeft: 10
    }






});

export default connect(state => ({
    storeState: state.store,
    memberState: state.member
}), dispatch => ({
    storeAction: bindActionCreators(storeActions, dispatch),
    memberAction: bindActionCreators(memberActions, dispatch)
}))(IndexPage)

